﻿using System;
using System.Collections.Generic;

namespace Dwarf.Managed
{
    /// <summary>Solve the Pattern Search Problem by FSM without parallelization</summary>
    ///
    class Solver
    {
        private Configurator dwarfConfigurator;             // processed settings from command line
        private List<int> positions;                        // search result

        /// <summary>Construct the new solver</summary>
        /// <param name="dwarfConfigurator">Processed command line arguments</param>
        /// 
        public Solver(ref Configurator dwarfConfigurator)
        {
            this.dwarfConfigurator = dwarfConfigurator;
            dwarfConfigurator.WriteSettings();               // write settings to console and profile file

        }

        /// <summary>Non-parallelized method of solving</summary>
        ///
        public void Solve()
        {
            string pattern = null;
            int[,] states = null;
            int previousContentPosition = 0;
            positions = new List<int>();                            // new list of founded positions

            dwarfConfigurator.GetData(ref pattern, 1);              // get pattern from inputfile            
            FiniteStateMachineBaseMethod.ConstructStates(ref states, pattern);  // create state array 
            string contentPart = dwarfConfigurator.GetNextInputPart();

            while (contentPart != null)
            {
                int contentPartLength = contentPart.Length - contentPart[contentPart.Length - 1] - 1;
                FiniteStateMachineBaseMethod fsmMethod = new FiniteStateMachineBaseMethod(pattern, states, previousContentPosition, contentPart);
                fsmMethod.SetContentLength(contentPartLength);
                fsmMethod.Solve();
                previousContentPosition += contentPartLength;
                contentPart = dwarfConfigurator.GetNextInputPart();
                positions.AddRange(fsmMethod.GetPositionsList());
            }
        }

        /// <summary>Problem results output</summary>
        /// <param name="time">Spent time</param>
        ///
        public void Finish(double time)
        {
            dwarfConfigurator.Close(time, positions);
            Console.WriteLine("Total count of pattern entries: " + positions.Count);           // write all the positions count (all positions will be written into the output file)   
        }
    }
}